﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using YunLuPos.DB.Service;
using YunLuPos.Entity;
using YunLuPos.Net;
using YunLuPos.Net.Http;

namespace YunLuPos.Worker
{
    public class SyncOrderWorker
    {
        private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(SyncOrderWorker));
        SaleOrderService saleOrderService = new SaleOrderService();
        SaleOrderNetService netService = NetServiceManager.getSaleOrderNetService();
        int mill;
        bool isOne;

        public void asynStart(Boolean isOne,int mill)
        {
            this.mill = mill;
            this.isOne = isOne;
            Thread thread = new Thread(new ThreadStart(ThreadMethod));//创建线程
            thread.IsBackground = true;
            thread.Name = "POS-SYNC";
            thread.Start();
        }

        void ThreadMethod()
        {
            if (this.isOne)
            {
                syncOrders();
            }else
            {
                while (true)
                {
                    syncOrders();
                    Thread.Sleep(this.mill);
                }
            }
        }

        public void syncOrders()
        {
            List<SaleOrder> orders = saleOrderService.listUnSyncOrder();
            if(orders != null && orders.Count > 0)
            {
                foreach(SaleOrder so in orders)
                {
                    SaleOrder fullOrder = saleOrderService.getFullOrder(so.orderCode);
                    if(fullOrder != null)
                    {
                        try
                        {
                            long l = netService.upload(fullOrder);
                            if(l == 1)
                            {
                                saleOrderService.synced(fullOrder);
                            }
                            DynamicInfoHoder.netIsAlive = true;
                        }
                        catch(NetException ne)
                        {
                            logger.Error(ne);
                            DynamicInfoHoder.netIsAlive = false;
                            break;
                        }
                        catch(BizError error)
                        {
                            logger.Info("单据同步错误"+fullOrder.orderCode+ error.getCode()+error.getMsg());
                        }
                    }
                }
            }
        }

        public void startWatcher()
        {
            //默认一分钟
            int syncTime = 10 * 60 * 1000;
            asynStart(false, syncTime);
        }

    }
}
